﻿using Microsoft.AspNetCore.Mvc.Filters;
using System.Linq;

namespace XUCore.Ddd.Domain
{
    /// <summary>
    /// FluentValidation 验证拦截（因使用动态API，自动验证失效，导致需要手工操作。）
    /// </summary>
    public class RequestCommandValidationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var commands = context.ActionArguments.Select(c => (c.Value as Command)).Where(c => c != null).ToList();

            commands.ForEach(c => c.IsValid());

            var failures = commands.SelectMany(c => c.GetErrors()).Where(c => c != null).ToList();

            if (failures.Count != 0)
            {
                throw new ValidationException(failures);
            }

            //context.ActionArguments?.ForEach(c => (c.Value as Command)?.IsVaild());
            base.OnActionExecuting(context);
        }
    }

    /// <summary>
    /// FluentValidation 验证拦截（因使用动态API，自动验证失效，导致需要手工操作。）
    /// </summary>
    public class RequestCommandValidationActionFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var commands = context.ActionArguments.Select(c => (c.Value as Command)).Where(c => c != null).ToList();

            commands.ForEach(c => c.IsValid());

            var failures = commands.SelectMany(c => c.GetErrors()).Where(c => c != null).ToList();

            if (failures.Count != 0)
            {
                throw new ValidationException(failures);
            }
            //context.ActionArguments?.ForEach(c => (c.Value as Command)?.IsVaild());
        }
    }
}
